<?php

declare(strict_types=1);

namespace app\common\service\sys;

use app\common\dao\sys\MenuDao;
use app\common\traits\ServiceTrait;
use app\common\dao\sys\RoleDao;
use app\common\dao\sys\UserRoleDao;
use app\common\dao\sys\UserRoleMenusDao;
use app\common\service\hrm\DeptService;

/**
 * 角色 - 业务
 * @author:kaige
 * @update:2022-06-13
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class RoleService
{
  protected $dao = null;

  public function __construct()
  {
    $this->dao = new RoleDao();
  }
  use ServiceTrait;

  /**
   * 重写 列表条件
   */
  public function _list_where($post)
  {
    $where = [];
    if (isset($post['name']) && $post['name'] != "") {
      $where[] = ['name', 'like', '%' . $post['name'] . '%'];
    }
    $result['where'] = $where;
    $result['field'] = [];
    $result['order'] = ['create_time' => 'desc'];
    return $result;
  }

  /**
   * 取角色的操作权限数组
   * @param $id
   * @return array
   */
  public function getRoleMenuData($role_id, $user_id)
  {
    $result = _err();
    $info = $this->dao->getInfoById($role_id);
    if (!$info) {
      return _err('角色不存在');
    }
    if (!$user_id) {
      return _err('未登录');
    }
    $userRoleDao = new UserRoleMenusDao();
    $permList  = $userRoleDao->getListAll(['user_role_id' => $role_id]);
    if ($permList) {
      $nodeList = array_column($permList, 'menu_id');
    } else {
      $nodeList = [];
    }
    $menuService = new MenuService();
    $manageMenu = $menuService->getMenuDataTree($user_id, 2); //当前登陆者的后台菜单树,权限is_auth 第二参传2
    $result['data'] = $menuService->setUserRoleMenuDtree($manageMenu['menu'], $nodeList);
    $result['status'] = true;
    return $result;
  }

  /**
   * 获取用户角色操作权限
   */
  public function getRoleAuth($user_id)
  {
    if ($user_id == config('kaige.super_id') || $user_id == 168 || $user_id == 438) {
      return ['roles' => ['ROOT'], 'perms' => []];
    }
    $menuDao = new MenuDao();
    $userRoleDao = new UserRoleDao();
    // 查角色,用户对应多角色
    $where = [];
    $where[] = ['user_id', '=', $user_id];
    $roles = $userRoleDao->getListAll($where); //找出所有绑定的角色
    $roles_code = [];
    $roles_id = [];
    if ($roles) {
      foreach ($roles as $v) {
        $roles_code[] = $v['code']; //角色代码加入数组 //角色代码 在前端为 权限名称
        $roles_id[] = $v['id'];
      }
    }
    $menulist = $menuDao->getRoleMenuData($roles_id, 2);
    $perms = [];
    if ($menulist) {
      foreach ($menulist as $val) {
        if ($val['menu_type'] == 3) {
          $perms[] = $val['node'];
        }
      }
    }
    return ['roles' => $roles_code, 'perms' => $perms];
  }

  /**
   * 获取用户角色 数据权限
   * @param int $user_id
   * @return array user_ids 用户ID集
   */
  public function getRoleDataAuth($user_id, $field)
  {
    $user_id = $user_id / 1;
    if ($user_id == config('kaige.super_id')) {
      return [[$field, '>', 0]]; //所有
    }
    $urs = new UserRoleService();
    $us = new UserService();
    $ds = new DeptService();
    $user = $us->getInfoById($user_id);
    $role_ids = $urs->getUserRoleAllId($user_id); //角色ids  1,3,4
    //存储不同角色的结果
    $arr = [];
    foreach ($role_ids as $k => $v) {
      $role = $this->getInfoById($v);
      if ($role) {
        $dp = $role['data_permission'];
        switch ($dp) {
          case 1: //所有
            $arr[] = [$field, '>', 0]; //所有用户ID
            break;
          case 3: //所在公司数据
            $company_id = $us->getCompanyIdByUserId($user_id);
            $arr[] = [$field, 'IN', $us->getUserIdByCompanyId($company_id)];
            break;
          case 4: //所在部门及以下数据
            $u_dept = $ds->inSubs($user['dept_id'], true);
            $arr[] = [$field, 'IN', $us->getUserIdByInDeptIds($u_dept)];
            break;
          case 5: //所在部门数据
            $arr[] = [$field, 'IN', $us->getUserIdByDeptId($user['dept_id'])];
            break;
          case 6: //仅本人数据
            $arr[] = [$field, '=', $user_id];
            break;
          case 7: //自定义数据
            $arr[] = [$field, 'IN', $role['user_ids']];
            break;
          default:
            $arr[] = [$field, '=', $user_id]; //默认只能看自个
            break;
        }
      }
    }
    //去重
    foreach ($arr as $k => $v) {
      $j = 0;
      foreach ($arr as $k1 => $v1) {
        if ($v === $v1) {
          $j++;
          if ($j > 1) unset($arr[$k]);
        }
      }
    }
    return $arr;
  }

  /**
   * 获取角色列表
   */
  public function getroleuser($data = [])
  {
    if (isset($data['id']) &&  $data['id'] > 0) {
      $urs = new UserRoleService();
      $uss = new UserService();
      $ids = $urs->getRoleAllUserId($data['id']);
      $where = [];
      $where[] = ['id', 'IN', $ids];

      if (isset($data['limit'])) {
        $limit = (int)$data['limit'];
      } else {
        $limit = 20;
      }
      if (isset($data['page'])) {
        $page = (int)$data['page'];
      } else {
        $page = 1;
      }
      $list = $uss->getLists($page, $limit, $where, ['id' => 'desc'], ['id,un,real_name,sex,dept_id,dept_id_name,ranking_id_name']);
      if ($list) {
        return _layui($list['count'], $list['data']);
      }
    }
    return _layui(0, []);
  }
}
